package eao;

import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import entity.User;
import entity.UserPicture;

/**
 * Session Bean implementation class EaoUserPicture
 */
@Stateless(mappedName = "eaoUserPicture")
@LocalBean
public class EaoUserPicture {

	@PersistenceContext
	private EntityManager em;
    /**
     * Default constructor. 
     */
    public EaoUserPicture() {
        // TODO Auto-generated constructor stub
    }
    
    public UserPicture find(int id) {
        return em.find(UserPicture.class, id);
    }

    public List<UserPicture> findByUserId(Integer id) {
    	try{
        	Query q = em.createQuery("SELECT up FROM UserPicture as up WHERE up.user.id=:id", UserPicture.class);
        	q.setParameter("id", id);
        	return q.getResultList();
        	
        }catch(NoResultException nre){
        	// this exception occurs when do not found any result to return
        	return null;
        }
        
    }
    
    public List<UserPicture> list() {
    	return em.createQuery("SELECT up FROM UserPicture up", UserPicture.class).getResultList();
    }

    public void create(UserPicture up) throws Exception {
        try{
        	em.persist(up);
        	em.flush();
        }catch (Exception e) {
        	throw new Exception(e.getMessage());
		}
    }

    public void update(UserPicture user) {
        em.merge(user);
    }

    public void delete(UserPicture user) {
        em.remove(em.contains(user) ? user : em.merge(user));
    }

 }
